import { toParam } from 'jax-base/utils/url'
import download from 'jax-base/utils/download'

export default {
  provide() {
    return {
      appPageList: this,
    }
  },
  mounted() {
    this.appReady()
  },
  data() {
    return {
      // 列表key
      appListKey: 'appList',

      // 默认查询参数
      appQuery: {},

      appModel: this.$route.meta.appModel,
      appApi: null,

      appDefaultDetail: {}, // 默认详情内容

      appShowDetail: false,
      appDetail: {},

      appList: [], // 列表数据

      // 总条数
      appTotal: 0,

      // 当前页数
      appPage: this.$route.query.pageSize || 1,

      // 每页条数
      appPageSize: this.$route.query.pageSize || 20,

      // 所选数据
      appSelectData: [],

      // 加载中
      appLoading: false,
    }
  },
  computed: {
    appSelectd() {
      return this.appSelectData && this.appSelectData.length
    },
    // 主键
    appId() {
      return this.$route.meta.appId || 'id'
    },
  },
  methods: {
    appReady() {
      if (this.appBeforeReady) this.appBeforeReady()

      // 让iframe中可以通过parent.vm调用父元素
      window.vm = this

      // 默认查询数据
      this.appDefaultQuery = {
        ...this.appQuery,
      }

      this.appQuery = {
        ...this.appQuery,
        ...this.$route.query,
      }

      if (!this.appApi) this.appApi = this.appModel

      if (this.appInit) this.appInit(true)
    },

    // 页面初始化、搜索、分页切换自动调用
    appInit() {
      if (this.appBeforeInit) this.appBeforeInit()

      this.appGetList()
    },

    appHandleSelectionChange(val) {
      this.appSelectData = val
    },

    // 获取列表数据
    appGetList(config = {}) {
      // if (this.appIsSearch) config.showLoading = '查询中...'
      this.appLoading = true

      // 后台使用
      this.$http
        .get(`${this.appApi}`, {
          params: {
            page: this.appPage,
            pageSize: this.appPageSize,
            ...this.appQuery,
          },
          ...config,
        })
        .then((res) => {
          // 获取数据后触发【不做数据修改，只做对页面进行相关值结构后赋值】
          if (this.appGetListAfter) this.appGetListAfter(res)

          this[this.appListKey] = res.list
          this.appTotal = res.total
          this.appPage = res.page
          this.appPageSize = res.pageSize
        })
        .finally(() => (this.appLoading = false))
    },

    // 删除
    appHandleDelete(item) {
      this.$confirm('确认删除?', '提示', {
        type: 'warning',
      }).then(() => {
        const id = item[this.appId]
        this.$http.delete(`${this.appApi}/${id}`).then((res) => {
          this.$message.success('删除成功')
          this.appInit()
        })
      })
    },

    // 添加
    appHandleAdd(data) {
      // this.appModalName = 'appAdd';
      // this.appModalData = {
      //     ...this.appDefaultDetail,
      // }

      // if (this.appBeforeAdd) this.appBeforeAdd()

      this.appShowDetail = true
      this.appDetail = {
        ...this.appDefaultDetail,
        ...data,
      }
    },

    // 编辑
    appHandleEdit(item) {
      const newData = { ...item }

      // if(this.appBeforeEdit) this.appBeforeEdit(newData)

      // 处理默认值
      if (this.appDefaultDetail) {
        for (const key in this.appDefaultDetail) {
          if (newData[key] === null || newData[key] === undefined) {
            newData[key] = this.appDefaultDetail[key]
          }
        }
      }

      this.appDetail = newData

      this.appShowDetail = true
    },

    /**
     * @description: 修改接口
     * @param {Object} item 修改的行数据
     * @param {Object} newItem 修改字段组成的对象
     * @param {String} confirmMsg 确认提示语
     * @param {String} successMsg 请求完成提示语
     */
    async appHandleUpdate(item, newItem, confirmMsg, successMsg) {
      return new Promise(async (resolve, reject) => {
        if (!item) return reject()

        if (confirmMsg) {
          try {
            await this.$confirm(confirmMsg)
          } catch (error) {
            reject(error)
            return
          }
        }

        this.$http.put(`${this.appApi}/${item[this.appId]}`, newItem).then((res) => {
          this.$message.success(successMsg || '操作成功')

          // const list = this[this.appListKey]

          // list.map((item, index) => {
          //   if (item.id == item.id) {
          //     const item = {
          //       ...item,
          //       ...newItem,
          //     }

          //     list[index] = item
          //   }
          // })

          // this[this.appListKey] = [...list]

          this.appInit()

          resolve()
        })
      })
    },

    // 内容保存新增或修改
    async appHandleSubmit(e) {
      if (e) e.preventDefault()

      let appDetail = {
        ...this.appDetail,
      }

      this.$refs.appForm.validate((valid) => {
        if (valid) {
          if (this.appBeforeSubmit) {
            const reulst = this.appBeforeSubmit(appDetail)
            if (reulst == false) return
          }

          const id = appDetail[this.appId]

          if (id) {
            this.$http.put(`${this.appApi}/${id}`, appDetail).then((res) => {
              this.appShowDetail = false

              this.$message.success('保存成功')
              this.appSearch()
            })
          } else {
            this.$http.post(`${this.appApi}`, appDetail).then((res) => {
              this.appShowDetail = false

              this.$message.success('添加成功')
              this.appReset()
            })
          }
        } else {
          // this.$message.warning(valid);
          return false
        }
      })
    },

    /**
     * 导出
     * @param {*} type 导出类型 0、导出当页 1、导出所有
     */
    appHandleExport(isAll = true) {
      this.$http
        .get(`${this.appApi || this.appModel}`, {
          params: {
            ...this.appQuery,
            isExport: 1,
            pageSize: isAll === true ? -1 : this.appPageSize,
          },
          responseType: 'blob',
          showLoading: '导出中...',
        })
        .then((res) => {
          const content = res // 返回的内容
          const fileName = res.headers['content-disposition'].split('filename="').pop().replace('"', '') // 下载文件名

          download(content, fileName)
        })
    },

    // 批量删除
    appHandleBatchDelete() {
      const idList = this.appSelectData.map((item) => item[this.appId])
      if (!idList || !idList.length) return this.$message.warning('请先选择数据')

      this.$confirm('确认批量删除?', '警告', {
        type: 'warning',
      }).then((res) => {
        this.$http.delete(`${this.appApi}/${idList.join(',')}`).then((res) => {
          this.$message.success('删除成功')
          this.appInit()
        })
      })
    },

    // 批量修改
    appHandleBatchUpdate(newData, confirm, successMsg) {
      const idList = this.appSelectData.map((item) => item[this.appId])
      if (!idList || !idList.length) return this.$message.warning('请先选择数据')

      this.$confirm(confirm || '确认操作?', '警告', {
        type: 'warning',
      }).then((res) => {
        this.$http.put(`${this.appApi}/${idList.join(',')}`, newData).then((res) => {
          this.$message.success(successMsg || '操作成功')
          this.appInit()
        })
      })
    },

    /**
     * 搜索
     */
    appSearch() {
      this.appIsSearch = true
      this.appPage = 1
      this.appTotal = 0
      this.appSetUrlQuery()
      this.appInit()
      this.appIsSearch = false
    },

    /**
     * 重置
     */
    appReset(isSearch = true) {
      let query = {
        ...this.appDefaultQuery,
      }

      this.appQuery = query
      if (isSearch) this.appSearch()
    },

    /**
     * 设置URL
     */
    appSetUrlQuery() {
      this.appQuery = {
        ...this.appQuery,
        page: this.appPage,
        pageSize: this.appPageSize,
      }

      // const newUrl = toParam(this.appQuery, location.origin + location.pathname)
      // history.replaceState(null, 'page' + Date.now(), newUrl)

      this.$router.replace({
        path: this.$route.path,
        query: this.appQuery,
      })
    },

    // 分页切换
    appHandlePageChange(page) {
      this.appPage = page

      this.appSetUrlQuery()
      this.appInit()
    },

    // 条数切换
    appHandleSizeChange(pageSize) {
      this.appPage = 1
      this.appPageSize = pageSize

      this.appSetUrlQuery()
      this.appInit()
    },
  },
}
